import { debugRun } from '@/components/cms/utils'
import Dexie, { type Table } from 'dexie'
import Config from '../config'
import type { EditorState } from '../types'

export interface EditorStore {
  id?: number
  value: string
}

export class EditorEditorClassedDexie extends Dexie {
  editorStore!: Table<EditorStore>
  constructor() {
    super(Config.projectSettings.dbName)
    this.version(1).stores({
      editorStore: '++id, value'
    })
  }
}

export const db = new EditorEditorClassedDexie()

let saveIng = false
/** 本地存储编辑器状态 */
export const saveEditorStateForLocal = async (editorState: any) => {
  const value = JSON.stringify(editorState)
  if (!saveIng) {
    debugRun(
      () => {
        console.log('数据保存 Start')
      },
      { debug: editorState.debug }
    )
    saveIng = true
    const count = await db.editorStore.count()
    if (count > 0) {
      const first = await db.editorStore.toCollection().first()
      db.editorStore.update(first!.id!, { value })
    } else {
      db.editorStore.add({ value })
    }
    setTimeout(() => {
      saveIng = false
    }, 800)
    debugRun(
      () => {
        console.log('数据保存 End')
      },
      { debug: editorState.debug }
    )
  }
}

export const getEditorStateForLocal = async (): Promise<EditorState> => {
  const count = await db.editorStore.count()
  if (count > 0) {
    console.log('读取数据库')
    const first = await db.editorStore.toCollection().first()
    return JSON.parse(first?.value as string) as EditorState
  }
  console.log('默认数据')
  return Config.projectSettings.defaultEditorState
}
